package com.yc.hotel.controller;

import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yc.hotel.dto.UserInfoDTO;
import com.yc.hotel.entity.UserInfo;
import com.yc.hotel.enums.ResultEnum;
import com.yc.hotel.service.IUserInfoService;
import com.yc.hotel.util.ConstantInfo;
import com.yc.hotel.util.SendEmailUtil;
import com.yc.hotel.util.StringUtil;
import com.yc.hotel.vo.ResultVO;

@RestController
@RequestMapping("/user")
public class UserInfoController {

	@Autowired 
	private IUserInfoService userInfoService;
	
	@Autowired
	private SendEmailUtil sendEmailUtil;

	@PostMapping("/reg")
	private ResultVO reg(UserInfo uf) {
		int result = userInfoService.reg(uf);
		if(result > 0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@PostMapping("/login")
	private ResultVO login(@RequestParam Map<String, Object> map, HttpSession session) {
		UserInfo user = userInfoService.login(map);
		if(user != null) {
			UserInfoDTO userDTO = new UserInfoDTO();
			BeanUtils.copyProperties(user, userDTO);
			session.setAttribute(ConstantInfo.CURRENTMEMBERINFO, userDTO);
			return new ResultVO(ResultEnum.SUCCESS, user);	
		}
		return new ResultVO(ResultEnum.LOGIN_ERROR);	
	}
	@GetMapping("/check")
	private ResultVO check(HttpSession session) {
		Object obj = session.getAttribute(ConstantInfo.CURRENTMEMBERINFO);
		if (obj == null) {
			return new ResultVO(ResultEnum.LOGIN_ERROR);
		}
		UserInfoDTO user = (UserInfoDTO)obj;
		return new ResultVO(ResultEnum.SUCCESS, user);
	}
	@GetMapping("/out")
	private ResultVO out(HttpSession session) {
		session.removeAttribute(ConstantInfo.CURRENTMEMBERINFO);
		
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	
	@PostMapping("/sendCode")
	public ResultVO sendCode(String nickName, String email, HttpSession session) {
		if (StringUtil.checkNull(nickName, email)) {
			return new ResultVO(ResultEnum.CHECK_ERROR);
		}
		String code = "";
		Random rd = new Random();
		while (code.length() < 6) {
			code += rd.nextInt(10);
		}

		if (sendEmailUtil.sendEmail(email, code, nickName)) {
			session.setAttribute(ConstantInfo.EMAILCHECKCODE, code);

			TimerTask task = new TimerTask() {

				@Override
				public void run() {
					session.removeAttribute(ConstantInfo.EMAILCHECKCODE);
				}
			};
			Timer timer = new Timer();
			timer.schedule(task, 180000);// 3秒后执行
			return new ResultVO(ResultEnum.SUCCESS, code);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
}
